package com.yike.user.strategy.login.type;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yike.common.constant.CommonConstant;
import com.yike.common.exception.BusinessException;
import com.yike.common.tool.CommonUtil;
import com.yike.common.tool.LoginUtil;
import com.yike.common.tool.StringUtil;
import com.yike.user.entity.User;
import com.yike.user.mapper.UserMapper;
import com.yike.user.param.LoginParam;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Sakura
 * @date 2024/8/27 16:26
 * 短信验证码登录
 */
@Component
@Log
public class SmsLoginStrategy implements LoginTypeStrategy {

    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(LoginParam loginParam) {
        // 手机号和验证码不能为空
        if (StringUtil.isEmpty(loginParam.getMobile()) || StringUtil.isEmpty(loginParam.getSmsCode())) {
            throw new BusinessException(500, "手机号或验证码不能为空");
        }

        // 如果验证码666666则不做校验
        if (!"666666".equals(loginParam.getSmsCode())) {
            // 校验短信验证码是否正确
            if (!commonUtil.checkCode(CommonConstant.SMS_CODE + loginParam.getMobile(),
                    loginParam.getSmsCode())) {
                throw new BusinessException(500, "短信验证码错误");
            }
        }

        // 获取当前登录用户信息，这里支持账号和手机号登录
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getMobile, loginParam.getMobile())
                .ne(User::getStatus, 0));
        if (ObjectUtil.isNull(user)) {
            // 创建一个用户
            user = new User();
            user.setMobile(loginParam.getMobile());
            user.setUserNo(StringUtil.random(32)); // 生成用户ID
            user.setNickname(loginParam.getMobile());
            user.setCreateBy(LoginUtil.getUserId());
            user.setStatus(1); // 状态为正常
            userMapper.insert(user);
        }

        return user;
    }
}
